package ui.swing;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Enumeration;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JToolBar;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

import ui.StockUI;
import ui.swing.table.AbstractTableUI;
import ui.swing.table.BenifitTable;
import ui.swing.table.FinalSelTable;
import ui.swing.table.IndustryTable;
import ui.swing.table.SinaIndustryTable;
import ui.swing.table.StockTable;
import util.DateUtil;
import data.LoadData;
import data.ReadAndWriteCareCode;
import data.SaveHistoryData;
import dataconnect.InsertStockDeal;

public class ManageUI {

	private JFrame frame;
	private JTree tree = new JTree();
	private JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
	private JToolBar toolBar = new JToolBar();
	private JPanel panel = new JPanel();
	private IndustryTable inta = new IndustryTable();
	private SinaIndustryTable sinta = new SinaIndustryTable();

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ManageUI window = new ManageUI();
//					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public ManageUI() {
//		initData();
		initialize();
	}

	static{
//		LoadData ld = new LoadData();
//		ld.loadAllData();
		try {
			UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel") ;
//			javax.swing.plaf.metal.MetalLookAndFeel
//			com.sun.java.swing.plaf.motif.MotifLookAndFeel
//			com.sun.java.swing.plaf.windows.WindowsLookAndFeel
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		} catch (InstantiationException e1) {
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			e1.printStackTrace();
		} catch (UnsupportedLookAndFeelException e1) {
			e1.printStackTrace();
		}
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setIconImage(Toolkit.getDefaultToolkit().getImage("image/title.jpg"));
		frame.setBackground(Color.WHITE);
		frame.getContentPane().setBackground(Color.WHITE);
		frame.getContentPane().setLayout(null);
		frame.setVisible(true);
		
		panel.setBackground(Color.WHITE);
		panel.setBounds(10, 50, 126, 518);
		frame.getContentPane().add(panel);
		
		tree.setModel(new DefaultTreeModel(
			new DefaultMutableTreeNode("Menue") {
				{
					DefaultMutableTreeNode node_1;
					node_1 = new DefaultMutableTreeNode("industry");
						node_1.add(new DefaultMutableTreeNode("ihead"));
						node_1.add(new DefaultMutableTreeNode("sinaIhead"));
					add(node_1);
					node_1 = new DefaultMutableTreeNode("stock");
						node_1.add(new DefaultMutableTreeNode("careAbout"));
						node_1.add(new DefaultMutableTreeNode("lowup"));
						node_1.add(new DefaultMutableTreeNode("batup"));
						node_1.add(new DefaultMutableTreeNode("speedup"));
						node_1.add(new DefaultMutableTreeNode("lineup"));
						node_1.add(new DefaultMutableTreeNode("standaverline"));
						node_1.add(new DefaultMutableTreeNode("priceUp"));
					add(node_1);
					node_1 = new DefaultMutableTreeNode("dealprice");
						node_1.add(new DefaultMutableTreeNode("overBigSell"));
						node_1.add(new DefaultMutableTreeNode("BigBug"));
					add(node_1);
					node_1 = new DefaultMutableTreeNode("message");
						node_1.add(new DefaultMutableTreeNode("goodNews"));
						node_1.add(new DefaultMutableTreeNode("badNews"));
						node_1.add(new DefaultMutableTreeNode("research"));
					add(node_1);
						node_1 = new DefaultMutableTreeNode("report");
						node_1.add(new DefaultMutableTreeNode("selected"));
						node_1.add(new DefaultMutableTreeNode("benitreport"));
					add(node_1);
				}
			}
		));
		expandTree(tree,true);
		tree.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                jTreeValueChanged(evt);
            }
        });
		panel.setLayout(new GridLayout(0, 1, 0, 0));
		panel.add(tree);
		
		
		tabbedPane.setBackground(Color.WHITE);
		tabbedPane.setBounds(143, 50, 780, 518);
		frame.getContentPane().add(tabbedPane);
		
		toolBar.setBackground(Color.WHITE);
		toolBar.setBounds(10, 10, 318, 30);
		frame.getContentPane().add(toolBar);
		
		final JButton btnBak = new JButton("BackUpData");
		btnBak.setBackground(Color.WHITE);
		btnBak.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				EventQueue.invokeLater(new Runnable() {
					public void run() {
						btnBak.setEnabled(false);
						System.out.println("back up......");
						try {
							long t = System.currentTimeMillis();
							File file = new File("historydata"+File.separator+"last.sto");
							String fileName = DateUtil.format(DateUtil.getThisDate());
							File file2 = new File("historydata"+File.separator+fileName+".sto");
							try {
								if(file.exists()){
									file.delete();
								}
								if(file2.exists()){
									file2.delete();
								}
								new SaveHistoryData().saveHistoryData();
								System.out.println("save file:"+(System.currentTimeMillis()-t));
								InsertStockDeal.insertStockData(fileName+".sto");
							} catch (IOException ioe) {
								ioe.printStackTrace();
							} catch (SQLException sqle) {
								sqle.printStackTrace();
							}
							long t2 = System.currentTimeMillis();
							System.out.println("备份完成:"+(t2-t));
						} catch (Exception e) {
							e.printStackTrace();
						}finally{
							btnBak.setEnabled(true);
						}
					}
				});
			}
		});
		toolBar.add(btnBak);
		
		JButton btnNewButton = new JButton("Quit");
		btnNewButton.setBackground(Color.WHITE);
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(tabbedPane.getSelectedComponent() instanceof AbstractTableUI){
					AbstractTableUI astable = (AbstractTableUI)tabbedPane.getSelectedComponent();
					astable.killModelThread();
				}
				tabbedPane.remove(tabbedPane.getSelectedComponent());
			}
		});
		toolBar.add(btnNewButton);
		
		JButton btnAddsel = new JButton("addsel");
		btnAddsel.setBackground(Color.WHITE);
		btnAddsel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				QueryUi dialog = new QueryUi();
				if(!"".equals(dialog.getResult())){
					ReadAndWriteCareCode.addCode(dialog.getResult());
				}
			}
		});
		toolBar.add(btnAddsel);
		
		JButton btnDeletecare = new JButton("deleteCare");
		btnDeletecare.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(tabbedPane.getSelectedComponent() instanceof AbstractTableUI){
					AbstractTableUI astable = (AbstractTableUI)tabbedPane.getSelectedComponent();
					String code = astable.getTable().getValueAt(astable.getTable().getSelectedRow(), 0).toString();
					ReadAndWriteCareCode.removeCode(code);
				}
			}
		});
		btnDeletecare.setBackground(Color.WHITE);
		toolBar.add(btnDeletecare);
		
		JButton btnNewButton_1 = new JButton("SWT");
		btnNewButton_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				EventQueue.invokeLater(new Runnable() {
					public void run() {
						try {
							StockUI window = new StockUI();
							window.open();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
			}
		});
		btnNewButton_1.setBackground(Color.WHITE);
		toolBar.add(btnNewButton_1);
		
		JButton btnShowdeal = new JButton("showdeal");
		btnShowdeal.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(tabbedPane.getSelectedComponent() instanceof AbstractTableUI){
					AbstractTableUI astable = (AbstractTableUI)tabbedPane.getSelectedComponent();
					int colIndex = astable.getTable().getColumn("code").getModelIndex();
					String code = astable.getTable().getValueAt(astable.getTable().getSelectedRow(),colIndex).toString();
					
					DealUI frame = new DealUI(code);
					frame.setVisible(true);
				}
			}
		});
		btnShowdeal.setBackground(Color.WHITE);
		toolBar.add(btnShowdeal);
		frame.setBounds(100, 100, 949, 639);
		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		
		JMenuBar menuBar = new JMenuBar();
		frame.setJMenuBar(menuBar);
		
		JMenu mnNewMenu = new JMenu("File");
		menuBar.add(mnNewMenu);
		
		JMenuItem mntmNewMenuItem = new JMenuItem("New menu item");
		mnNewMenu.add(mntmNewMenuItem);
		
		JMenu mnNewMenu_1 = new JMenu("Data");
		menuBar.add(mnNewMenu_1);
		
		JMenuItem mntmNewMenuItem_1 = new JMenuItem("New menu item");
		mnNewMenu_1.add(mntmNewMenuItem_1);
		
		frame.addComponentListener(new ComponentAdapter() {
			@Override
			public void componentResized(ComponentEvent e) {
				toolBar.setSize(frame.getWidth()-30, 30);
				tabbedPane.setSize(frame.getWidth()-180, frame.getHeight()-120);
				panel.setSize(126,frame.getHeight()-120);
			}
		});
	}

	private void jTreeValueChanged(javax.swing.event.TreeSelectionEvent evt) {
		DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree
				.getLastSelectedPathComponent();// 返回最后选定的节点
		if (selectedNode.isLeaf()) {
			if ("ihead".equals(selectedNode.toString())) {
				tabbedPane.addTab(selectedNode.toString(), null, inta, null);
				tabbedPane.setSelectedComponent(inta);
			}else if("sinaIhead".equals(selectedNode.toString())){
				tabbedPane.addTab(selectedNode.toString(), null, sinta, null);
				tabbedPane.setSelectedComponent(sinta);
			}else if("careAbout".equals(selectedNode.toString())){
				StockTable stCareabout = new StockTable(1);
				tabbedPane.addTab(selectedNode.toString(), null, stCareabout, null);
				tabbedPane.setSelectedComponent(stCareabout);
			}else if("lowup".equals(selectedNode.toString())){
				StockTable stLowUp = new StockTable(5);
				tabbedPane.addTab(selectedNode.toString(), null, stLowUp, null);
				tabbedPane.setSelectedComponent(stLowUp);
			}else if("batup".equals(selectedNode.toString())){
				StockTable stBigDeal = new StockTable(8);
				tabbedPane.addTab(selectedNode.toString(), null, stBigDeal, null);
				tabbedPane.setSelectedComponent(stBigDeal);
			}else if("speedup".equals(selectedNode.toString())){
				StockTable stspeedUp = new StockTable(7);
				tabbedPane.addTab(selectedNode.toString(), null, stspeedUp, null);
				tabbedPane.setSelectedComponent(stspeedUp);
			}else if("lineup".equals(selectedNode.toString())){
				StockTable stUpline = new StockTable(9);
				tabbedPane.addTab(selectedNode.toString(), null, stUpline, null);
				tabbedPane.setSelectedComponent(stUpline);
			}else if("standaverline".equals(selectedNode.toString())){
				StockTable stStandAver = new StockTable(6);
				tabbedPane.addTab(selectedNode.toString(), null, stStandAver, null);
				tabbedPane.setSelectedComponent(stStandAver);
			}else if("priceUp".equals(selectedNode.toString())){
				tabbedPane.addTab(selectedNode.toString(), null, sinta, null);
			}else if("overBigSell".equals(selectedNode.toString())){
				tabbedPane.addTab(selectedNode.toString(), null, sinta, null);
			}else if("BigBug".equals(selectedNode.toString())){
				tabbedPane.addTab(selectedNode.toString(), null, sinta, null);
			}else if("goodNews".equals(selectedNode.toString())){
				tabbedPane.addTab(selectedNode.toString(), null, sinta, null);
			}else if("badNews".equals(selectedNode.toString())){
				tabbedPane.addTab(selectedNode.toString(), null, sinta, null);
			}else if("research".equals(selectedNode.toString())){
				tabbedPane.addTab(selectedNode.toString(), null, sinta, null);
			}else if("selected".equals(selectedNode.toString())){
				FinalSelTable stFinalsel = new FinalSelTable();
				tabbedPane.addTab(selectedNode.toString(), null, stFinalsel, null);
				tabbedPane.setSelectedComponent(stFinalsel);
			}else if("benitreport".equals(selectedNode.toString())){
				BenifitTable benifitTable = new BenifitTable();
				tabbedPane.addTab(selectedNode.toString(), null, benifitTable, null);
				tabbedPane.setSelectedComponent(benifitTable);
			}
			
			System.out.println(selectedNode.toString());
		}

	}

	private void expandTree(JTree tree, boolean bo) {
		TreeNode root = (TreeNode) tree.getModel().getRoot();
		expandAll(tree, new TreePath(root), bo);
	}

	private void expandAll(JTree tree, TreePath parent, boolean expand) {
		TreeNode node = (TreeNode) parent.getLastPathComponent();
		if (node.getChildCount() >= 0) {
			for (Enumeration<TreeNode> e = node.children(); e.hasMoreElements();) {
				TreeNode n = (TreeNode) e.nextElement();
				TreePath path = parent.pathByAddingChild(n);
				expandAll(tree, path, expand);
			}
		}
		if (expand) {
			tree.expandPath(parent);
		} else {
			tree.collapsePath(parent);
		}
	}
}
